// 标签内有 nolazy 时将不再懒加载
export default function lazyImagePlugin() {
  const fileRegex = /\.(vue)$/;
  const codeRegex = /(<img)([^>]+src=[\"|\'][^>]+[\"|\'][^>]*\/>)/g;
  const noLazyRegex = /(<img\s+)(loading\=\"lazy\")([^>]*nolazy[^>]*\/>)/g;
  return {
    name: "vite-plugin-lazyimage",
    enforce: "pre",
    transform(src, id) {
      if (fileRegex.test(id)) {
        src = src.replace(codeRegex, '$1 loading="lazy" $2');
        src = src.replace(noLazyRegex, "$1 $3");
      }
      return {
        code: src,
      };
    },
  };
}
